// ignore_for_file: unused_field

import 'package:flutter/material.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';
import 'package:weichat_post/entity/menu.dart';
import 'package:weichat_post/utils/index.dart';
import 'package:weichat_post/widgets/index.dart';
import 'package:wechat_camera_picker/wechat_camera_picker.dart';

enum PostType { image, video }

/// 发布界面
class PostEditPage extends StatefulWidget {
  const PostEditPage({
    super.key,
    this.postType,
    this.selectedAssets,
  });

  // 发布类型
  final PostType? postType;

  // 已选择的照片列表
  final List<AssetEntity>? selectedAssets;

  @override
  State<PostEditPage> createState() => _PostEditPageState();
}

class _PostEditPageState extends State<PostEditPage> {
  // 发布类型
  PostType? _postType;

  // 已选择的照片列表
  List<AssetEntity> _selectedAssets = [];

  // 是否开始拖拽
  bool _isDragNow = false;

  // 是否将要删除
  bool _isWillRemove = false;

  // 是否将要排序
  bool _isWillOrder = false;

  // 被拖拽到的 target id
  String _targetAssetId = "";

  // 视频压缩文件
  CompressMediaFile? _videoCompressFile;

  // 内容输入控制器
  final TextEditingController _contentController = TextEditingController();

  // 菜单列表
  List<MenuItemModel> _menus = [];

  @override
  void initState() {
    super.initState();
    _postType = widget.postType;
    _selectedAssets = widget.selectedAssets ?? [];

    _menus = [
      MenuItemModel(icon: Icons.location_on_outlined, title: "所在位置"),
      MenuItemModel(icon: Icons.attach_email_outlined, title: "提醒谁看"),
      MenuItemModel(icon: Icons.person_outline, title: "谁可以看", right: "公开"),
    ];
  }

  @override
  void dispose() {
    _contentController.dispose();
    super.dispose();
  }


  // 内容输入框
  Widget _buildContentInput() {
    return LimitedBox(
      maxHeight: 180,
      child: TextField(
        maxLength: 20,
        maxLines: null,
        controller: _contentController,
        decoration: InputDecoration(
          hintText: "这一刻的想法...",
          hintStyle: const TextStyle(
            color: Colors.black12,
            fontSize: 18,
            fontWeight: FontWeight.w500,
          ),
          border: InputBorder.none,
          counterText: _contentController.text.isEmpty ? "" : null,
        ),
        onChanged: (value) {
          setState(() {});
        },
      ),
    );
  }

  // 菜单项目

  Widget _buildMenus() {
    List<Widget> ws = [];
    ws.add(const DividerWidget());
    for (var menu in _menus) {
      ws.add(ListTile(
        leading: Icon(menu.icon),
        title: Text(menu.title!),
        trailing: Text(menu.right ?? "",style: const TextStyle(fontSize: 15),),
        onTap: menu.onTap,
      ));
      ws.add(const DividerWidget());
    }

    return Padding(
      padding: const EdgeInsets.only(top: 100),
      child: Column(
        children: ws,
      ),
    );
  }

  // 图片列表
  Widget _buildPhotosList() {
    return Padding(
      padding: const EdgeInsets.all(spacing),
      child: LayoutBuilder(
          builder: (BuildContext context, BoxConstraints constraints) {
        final double width =
            (constraints.maxWidth - spacing * 2 - imgPadding * 2 * 3) / 3;

        return Wrap(
          spacing: spacing,
          runSpacing: spacing,
          children: [
            // 图片列表
            for (final asset in _selectedAssets) _buildPhotoItem(asset, width),
            // 选择图片按键
            if (_selectedAssets.length < maxAssets)
              _buildAddBtn(context, width),
          ],
        );
      }),
    );
  }

  // 添加按钮
  GestureDetector _buildAddBtn(BuildContext context, double width) {
    return GestureDetector(
      onTap: () async {
        final result = await DuBottomSheet(selectedAssets: _selectedAssets)
            .wxPicker<List<AssetEntity>>(context);
        if (result == null || result.isEmpty) {
          return;
        }

        if (result.length == 1 && result.first.type == AssetType.video) {
          setState(() {
            _postType = PostType.video;
            _selectedAssets = result;
          });
        } else {
          setState(() {
            _postType = PostType.image;
            _selectedAssets = result;
          });
        }
      },
      child: Container(
        clipBehavior: Clip.antiAlias,
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(5),
          color: Colors.black12,
        ),
        width: width,
        height: width,
        child: const Icon(
          Icons.add,
          size: 48,
          color: Colors.black38,
        ),
      ),
    );
  }

  // 图片项
  Widget _buildPhotoItem(AssetEntity asset, double width) {
    return Draggable<AssetEntity>(
      data: asset,

      // 当拖拽对象开始被拖拽时调用
      onDragStarted: () {
        setState(() {
          _isDragNow = true;
        });
      },

      //当拖拽对象开始放下时候调用
      onDragEnd: (details) {
        setState(() {
          _isDragNow = false;
          _isWillOrder = false;
        });
      },

      // 当可拖动对象被拖放并被[DragTarget]接受时调用。
      onDragCompleted: () {},

      // 当可拖动对象未被 [DragTarget] 接受而被放置时调用。
      onDraggableCanceled: (velocity, offset) {
        setState(() {
          _isDragNow = false;
          _isWillOrder = false;
        });
      },

      // 拖动进行时显示在指针下方的小部件
      feedback: Container(
        clipBehavior: Clip.antiAlias,
        decoration: BoxDecoration(borderRadius: BorderRadius.circular(5)),
        child: AssetEntityImage(
          asset,
          width: width,
          height: width,
          fit: BoxFit.cover,
          isOriginal: false,
        ),
      ),

      childWhenDragging: Container(
        clipBehavior: Clip.antiAlias,
        decoration: BoxDecoration(borderRadius: BorderRadius.circular(5)),
        child: AssetEntityImage(
          asset,
          width: width,
          height: width,
          fit: BoxFit.cover,
          isOriginal: false,
          opacity: const AlwaysStoppedAnimation(0.2),
        ),
      ),

      child: DragTarget<AssetEntity>(
        builder: (context, candidateData, rejectedData) {
          return GestureDetector(
            onTap: () {
              Navigator.push(context, MaterialPageRoute(builder: (context) {
                return GalleryWidget(
                    initialIndex: _selectedAssets.indexOf(asset),
                    items: _selectedAssets);
              }));
            },
            child: Container(
              clipBehavior: Clip.antiAlias,
              padding: (_isWillOrder && _targetAssetId == asset.id)
                  ? EdgeInsets.zero
                  : const EdgeInsets.all(imgPadding),
              decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(5),
                  border: (_isWillOrder && _targetAssetId == asset.id)
                      ? Border.all(color: accentColor, width: imgPadding)
                      : null),
              child: ClipRRect(
                borderRadius: (_isWillOrder && _targetAssetId == asset.id)
                    ? BorderRadius.circular(0)
                    : BorderRadius.circular(5),
                child: AssetEntityImage(
                  asset,
                  width: width,
                  height: width,
                  fit: BoxFit.cover,
                  isOriginal: false,
                ),
              ),
            ),
          );
        },
        onAcceptWithDetails: (details) {
          final int index = _selectedAssets.indexOf(details.data);
          _selectedAssets.removeAt(index);
          final int targetIndex = _selectedAssets.indexOf(asset);
          _selectedAssets.insert(targetIndex, details.data);
          setState(() {
            _isWillOrder = false;
            _targetAssetId = "";
          });
        },
        onWillAcceptWithDetails: (details) {
          setState(() {
            _isWillOrder = true;
            _targetAssetId = asset.id;
          });
          return true;
        },
        onLeave: (data) {
          setState(() {
            _isWillOrder = false;
            _targetAssetId = "";
          });
        },
      ),
    );
  }

  // 删除 bar
  Widget _buildRemoveBar() {
    return DragTarget<AssetEntity>(
      builder: (context, candidateData, rejectedData) {
        return SizedBox(
          width: double.infinity,
          child: Container(
            height: 120,
            width: 10000,
            color: _isWillRemove ? Colors.red[500] : Colors.red[200],
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Text(
                  _isWillRemove ? "松开即可删除" : "删除",
                  style: TextStyle(
                    fontSize: 18,
                    color: _isWillRemove ? Colors.white : Colors.white54,
                  ),
                ),
                Icon(
                  Icons.delete,
                  size: 32,
                  color: _isWillRemove ? Colors.white : Colors.white54,
                )
              ],
            ),
          ),
        );
      },
      onWillAcceptWithDetails: (details) {
        setState(() {
          _isWillRemove = true;
        });
        return true;
      },
      onAcceptWithDetails: (details) {
        setState(() {
          _selectedAssets.remove(details.data);
          _isWillRemove = false;
        });
      },
      onLeave: (data) {
        setState(() {
          _isWillRemove = false;
        });
      },
    );
  }

  // 主视图
  Widget _mainView() {
    return Scaffold(
      appBar: AppBarWidget(
        // 左侧返回
        leading: GestureDetector(
          onTap: () {
            Navigator.pop(context);
          },
          child: const Padding(
            padding: EdgeInsets.only(left: pagePadding),
            child: Text("取消",style: TextStyle(fontSize: 18),),
          ),
        ),
        // 右侧发布
        actions: [
          Padding(
            padding: const EdgeInsets.only(right: pagePadding),
            child: ElevatedButton(
              onPressed: () {},
              style: ButtonStyle(
                shape: WidgetStatePropertyAll(
                  RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(5),
                  ),
                ),
                backgroundColor: const WidgetStatePropertyAll(Colors.green),
                foregroundColor: const WidgetStatePropertyAll(Colors.white),
              ),
              child: const Text("发布",style: TextStyle(fontWeight: FontWeight.bold),),
            ),
          ),
        ],
      ),
      body: GestureDetector(
        onTap: (){
            FocusScope.of(context).unfocus();
        },
        child: SingleChildScrollView(
          child: Padding(
            padding: const EdgeInsets.all(pagePadding),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // 内容输入
                _buildContentInput(),
          
                // 图片列表
                if (_postType == PostType.image) _buildPhotosList(),
          
                // 视频播放器
                if (_postType == PostType.video)
                  VideoPlayWidget(
                    initAsset: _selectedAssets.first,
                    onCompleted: (value) => _videoCompressFile = value,
                  ),
          
                // 添加按钮
                if (_postType == null && _selectedAssets.isEmpty)
                  Padding(
                    padding: const EdgeInsets.all(spacing),
                    child: _buildAddBtn(context, 100),
                  ),
          
                // 菜单项
                _buildMenus(),
              ],
            ),
          ),
        ),
      ),
      bottomSheet: _isDragNow ? _buildRemoveBar() : null,
    );
  }

  @override
  Widget build(BuildContext context) {
    return _mainView();
  }
}
